package com.rybbaby.tss.platform.sysMenuPermissions.service.imp;

import com.rybbaby.tss.core.utils.AjaxJsonResponse;
import com.rybbaby.tss.core.web.service.imp.BaseServiceImp;
import com.rybbaby.tss.platform.initializer.MenuPermissionsInitializer;
import com.rybbaby.tss.platform.initializer.SysConfigInitializer;
import com.rybbaby.tss.platform.sysHandlePermissions.service.ISysHandlePermissionsService;
import com.rybbaby.tss.platform.sysMenuPermissions.entity.SysMenuPermissions;
import com.rybbaby.tss.platform.sysMenuPermissions.service.ISysMenuPermissionsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 谢进伟
 * @description 菜单权限数据库操作服务实现
 * @createDate 2016-08-19 上午11:36:25
 */
@Service
@Transactional
public class SysMenuPermissionsServiceImp extends BaseServiceImp<SysMenuPermissions> implements ISysMenuPermissionsService {

    @Autowired
    private ISysHandlePermissionsService sysHandlePermissionsService;

    @Override
    public List<Map<String, Object>> pIdDatasource() {
        String sql1 = "SELECT id,name FROM sys_menu_permissions";
        List<Map<String, Object>> pId_datasources = this.findForJdbc(sql1, null);
        return pId_datasources;
    }

    @Override
    public boolean updateMenuPermissionWeight(List<Object[]> sortWeghtList, Map<String, List<String>> referenceMap) {
        if (referenceMap != null && !referenceMap.isEmpty()) {
            Set<String> keySet = referenceMap.keySet();
            for (String key : keySet) {
                List<String> list = referenceMap.get(key);
                String sql = "UPDATE sys_menu_permissions SET pId=? WHERE id IN('" + StringUtils.join(list.toArray(), "','") + "')";
                super.executeSql(sql, new Object[]{"root".equals(key) ? null : key});
            }
        }
        String sql = "UPDATE sys_menu_permissions SET weight=? WHERE id=?";
        return super.batchUpdate(sql, sortWeghtList);
    }

    @Override
    public List<SysMenuPermissions> getAdminUserMenuPermissions(String adminUserId) throws Exception {
        StringBuffer sql = new StringBuffer("SELECT id, pId, name, icon, url, weight, isForbidden, createTime, createUserId, version FROM sys_menu_permissions WHERE 1=1 ");
        // 未被禁用菜单
        sql.append(" AND isForbidden=0 ");
        sql.append(" AND (");
        // 私有菜单权限
        sql.append("id IN(SELECT menuPermissionId FROM sys_admin_user_join_sys_menu_permissions WHERE adminUserId=?)");
        // 所属有角色所拥有的菜单权限
        sql.append(" OR id IN(SELECT menuPermissionsId FROm sys_role_join_sys_menu_permissions WHERE roleId IN(SELECT roleId FROM sys_admin_user_join_sys_role WHERE adminUserId=? AND isForbidden=0))");
        sql.append(")");
        return this.findListBySql(sql.toString(), new Object[]{adminUserId, adminUserId});
    }

    @Override
    public String saveOrUpdateMeenuPermission(SysMenuPermissions entity, Object loginUserId_obj) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            String id = entity.getId();
            ajr.setResMsg("保存成功!");
            Object defaultMeunNameCharCount = SysConfigInitializer.getConfigValueByConfigName("defaultMeunNameCharCount", 8);// 菜单名字最大字符数
            if (entity.getName().length() > Integer.parseInt(defaultMeunNameCharCount.toString())) {
                ajr.setResCode(301);
                ajr.setResMsg("保存失败(菜单名最大为" + defaultMeunNameCharCount + "个字符)!");
            } else {
                boolean isUpdate = true;
                if (StringUtils.isNotBlank(id)) {
                    SysMenuPermissions destEntity = this.get(id);
                    String handlePermissionIdentifier = destEntity.getHandlePermissionIdentifier();
                    if (handlePermissionIdentifier != null && !handlePermissionIdentifier.equals(entity.getHandlePermissionIdentifier())) {
                        isUpdate = handlePermissionIdentifierIsExists(entity, ajr);
                    }
                    if (isUpdate) {
                        BeanUtils.copyProperties(entity, destEntity, "createTime", "weight");
                        if (destEntity.getCreateUserId() == null) {
                            destEntity.setCreateUserId(loginUserId_obj.toString());
                        }
                        this.updateEntitiy(destEntity);
                        MenuPermissionsInitializer.load();
                    }
                } else {
                    isUpdate = handlePermissionIdentifierIsExists(entity, ajr);
                    if (isUpdate) {
                        entity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                        String loginUserId = loginUserId_obj == null ? null : loginUserId_obj.toString();
                        entity.setCreateUserId(loginUserId);
                        Serializable newId = this.save(entity);
                        if (newId == null) {
                            ajr.setResCode(301);
                            ajr.setResMsg("保存失败!");
                        } else {
                            sysHandlePermissionsService.initMenuDefaultHandle(newId.toString(), loginUserId);
                            MenuPermissionsInitializer.load();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 判断菜单权限的操作权限标识是否存在
     *
     * @param entity 菜单权限对象
     * @param ajr    ajax响应对象
     * @return
     */
    private boolean handlePermissionIdentifierIsExists(SysMenuPermissions entity, AjaxJsonResponse ajr) {
        boolean isUpdate = true;
        List<SysMenuPermissions> existsHandlePermissionIdentifier = this.findByProperty("handlePermissionIdentifier", entity.getHandlePermissionIdentifier());
        if (existsHandlePermissionIdentifier != null && !existsHandlePermissionIdentifier.isEmpty()) {
            ajr.setResCode(301);
            ajr.setResMsg("保存失败(操作权限标识已存在)!");
            isUpdate = false;
        }
        return isUpdate;
    }
}
